import UIKit

var s_GofButtonTouchDownKey = "s_GofButtonTouchDownKey";
var s_GofButtonTouchUpKey = "s_GofButtonTouchUpKey";

extension UIControl
{
    
    public typealias GofBtnClickBlock = (UIButton)->Void;
    
    /// 按钮TouchDown
    var gof_touchDown: GofBtnClickBlock? {
        get{
            let touchDown = objc_getAssociatedObject(self, &s_GofButtonTouchDownKey);
            let dealTouchDown = unsafeBitCast(touchDown, to: GofBtnClickBlock.self);
      
            return dealTouchDown;
        }
        set(touchDown)
        {
            let dealTouchDown: AnyObject = unsafeBitCast(touchDown,to:AnyObject.self);
            objc_setAssociatedObject(self, &s_GofButtonTouchDownKey, dealTouchDown, .OBJC_ASSOCIATION_COPY);
            
            self.removeTarget(self, action: #selector(onTouchDown(btn:)), for: UIControl.Event.touchDown);
            self.addTarget(self, action: #selector(onTouchDown(btn:)), for: UIControl.Event.touchDown);
        }
    }
    
    /// 按钮TouchUpInside
    var gof_touchUpInside: GofBtnClickBlock? {
        get{
            let touchUp = objc_getAssociatedObject(self, &s_GofButtonTouchUpKey) as? GofBtnClickBlock;
            //let dealTouchUp = unsafeBitCast(touchUp,to: GofBtnClickBlock.self);
            return touchUp;
        }
        set(touchUp)
        {
           // let dealTouchUp: GofBtnClickBlock = unsafeBitCast(touchUp, to: GofBtnClickBlock.self);
            objc_setAssociatedObject(self, &s_GofButtonTouchUpKey, touchUp, .OBJC_ASSOCIATION_COPY);
            self.removeTarget(self, action: #selector(onTouchUp(btn:)), for: UIControl.Event.touchUpInside);
            self.addTarget(self, action: #selector(onTouchUp(btn:)), for: UIControl.Event.touchUpInside);
        }
    }
    
    /**
     按钮TouchDown事件处理
     
     - parameter btn: 按钮
     */
    @objc func onTouchDown(btn: UIButton) -> Void
    {
        let touchDown = self.gof_touchDown;
        if touchDown != nil
        {
            touchDown!(btn);
        }
        
    }
    
    /**
     按钮TouchUpInside事件处理
     
     - parameter btn: 按钮
     */
    @objc func onTouchUp(btn: UIButton) -> Void
    {
        let touchUp = self.gof_touchUpInside;
        if touchUp != nil
        {
            touchUp!(btn);
        }
    }
    
    
    
}
